//
//  CPrimmer.c
//  CProject
//
//  Created by 黄小刚 on 2018/9/4.
//  Copyright © 2018年 黄小刚. All rights reserved.
//

#include "CPrimmer.h"
#include <stdlib.h>
#include <string.h>

/**
    动态分配内存
 */
void creatMalloc (void) {
    
    // 动态创建一个整形指针变量
    // (int *) malloc(sizeof(int))返回的是一个地址
    int *pi = (int *) malloc(sizeof(int));
    // 为整型指针变量赋值
    *pi = 10;
    
    printf("*pi: %d\n", *pi);
    
    // 释放内存
    free(pi);
    
}


void mallocDemo0 (void) {
    
    // 字符数组的长度不能跟循环的长度一致，因为默认字符数组最后一个是NUL字符
    char * pc = (char *) malloc(sizeof(char) * 9);
    
    for (int i = 0; i < 8; i ++) {
        pc[i] = 'w';
    }
    printf("pc:%s \n",pc);
    free(pc);
}

void mallocDemo1 (void) {
    
    // 字符数组的长度不能跟循环的长度一致，因为默认字符数组最后一个是NUL字符
    char *name = (char *) malloc(strlen("Susan") + 1);
    strcpy(name,"Susan");
    
    printf("name=>%s\n",name);
  
    // 静态指针
//    static int *pi ;
//    pi = (int *) malloc(sizeof(int));
}

void callocDemo0 (void) {
    
    int *pi = calloc(5, sizeof(int));
    
    printf("*pi = %d %p\n",*pi,pi);
    for (int i = 0; i < 5; i ++) {
        pi[i] = 1;
    }
    
    for (int i = 0; i < 5; i ++) {
        printf("pi[i] => %d\n",pi[i]);
    }
    
    
    char * string1;
    char * string2;
    string1 = (char *) malloc(16);
    strcpy(string1, "0123456789A");
    
    string2 = realloc(string1, 8);
    
    printf("string1 value:%p [%s]\n",string1,string1);
    printf("string2 value:%p [%s]\n",string2,string2);

}

void mallocDemoMain (void) {
    callocDemo0();
}
